const cron = require('node-cron');
const ocentCrawlerService = require('./services/ocentCrawler');
const mongoose = require('mongoose');
const dotenv = require('dotenv');

// Load environment variables
dotenv.config();

// Move function definition to top level
function startOcentCrawlerSchedule() {
  console.log('Starting Ocent crawler scheduled task...');

  // Define hourly scheduled task
  const task = cron.schedule('0 * * * *', async () => {
    try {
      console.log(`[${new Date().toLocaleString()}] Starting Ocent crawler task...`);
      
      // Process product information - using actual product ID
      const result = await ocentCrawlerService.processProduct(790);
      
      if (!result) {
        console.error(`[${new Date().toLocaleString()}] Ocent product processing failed`);
      }
      
      console.log(`[${new Date().toLocaleString()}] Ocent crawler task completed`);
    } catch (error) {
      console.error(`[${new Date().toLocaleString()}] Ocent crawler task execution error:`, error);
    }
  });

  console.log('Ocent crawler scheduled task started, running...');
  return task;
}

// Export function at top level
module.exports = { startOcentCrawlerSchedule };

// If this file is run directly, connect to database and start crawler
if (require.main === module) {
  const DB_HOST = process.env.DB_HOST || '10.0.55.56';
  const DB_PORT = process.env.DB_PORT || '27017';
  const DB_NAME = process.env.DB_NAME || 'metroCrawlerTest';
  
  console.log(`Attempting to connect to database: mongodb://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`);
  mongoose.connect(`mongodb://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`)
    .then(() => {
      console.log('Successfully connected to MongoDB');
      startOcentCrawlerSchedule();
    })
    .catch(err => {
      console.error('MongoDB connection error:', err);
    });
} 